const express = require('express')
const path = require('path')
const chalk = require('chalk')
const http = require('http')
const cors = require('cors')
require('module-alias/register')
// 访问 .env文件
const dotenv = require('dotenv')
dotenv.config()


// 路由加载
const mount = require('mount-routes') 
// const useRoute = require('./routes/useRoute')

const app = express()

const bodyParser = require('body-parser')
const multiparty = require('connect-multiparty')

// 处理 x-www-form-urlencoded
app.use(bodyParser.urlencoded({
    extended:true
}));
// 处理 application/json
app.use(bodyParser.json())
// 处理 mutipart/form-data
app.use(multiparty())


// 跨域处理
app.use(cors())

app.all('/api/*', (req, res,next) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'X-Request-With, token')
    res.header('Access-Control-Allow-Headers', 'X-Request-With, Authrization')
    res.setHeader('Content-Type', 'application/json;charset=utf-8')
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length,Authrization,Accept,X-Request-With')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header('X-Powered-By', ' 3.2.1')
    if (req.method == 'OPTIONS')  res.send(200)
    /*让options请求快速返回*/ else next()
})

// 初始化统一响应机制
const sendResult = require('./modules/sendResult')
app.use(sendResult)

/** 后台管理系统 */

const { pcLogin } = require('./controller/userController')
// 初始化后台登录passport 策略
const { setup, login, tokenAuth } = require('./modules/token')
// 设置登录模块的登录函数衔接passport 策略
setup(app, pcLogin)
// 设置passport登录入口点
app.use('/api/private/pcLogin', login)
// 设置passport验证其他请求
app.use('/api/private/*',tokenAuth)


// 根据routes路径来自动加载路由方式
mount(app, path.join(process.cwd(), '/routes'), true)
// app.use('/', useRoute)

// 使用Swagger API 文档
// https://www.npmjs.com/package/express-swagger-generator
const expressSwagger = require('express-swagger-generator')(app)
const swag_config = require('./config/swag.config')
expressSwagger(swag_config)

// const server =  http.createServer(app)
// server.listen(8888, () => {
//     console.log(chalk.bold.red('应用已启动!, http://127.0.0.1:8888'))
// })

app.listen(process.env.DEV_PORT, () => {
    console.log(chalk.bold.green(`项目启动成功: ${process.env.DEV_URL}:${process.env.DEV_PORT}`))
    console.log(chalk.bold.green(`接口文档地址: ${process.env.DEV_URL}:${process.env.DEV_PORT}/swagger`));
})